package com.frank.twloading;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;

import java.util.ArrayList;
import java.util.Optional;

/**
 * @author : frank
 * @date : 2021/4/30 16:38
 */
public class ComponentItemProvider extends BaseItemProvider {

    public ArrayList<Component> componentArrayList;

    private int column;

    public ComponentItemProvider(ArrayList<Component> componentArrayList, int col) {
        this.componentArrayList = componentArrayList;
        this.column = col;
    }

    @Override
    public int getCount() {
        return componentArrayList.size();
    }

    @Override
    public Object getItem(int i) {
        return componentArrayList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component convertComponent, ComponentContainer componentContainer) {
        Component component = componentArrayList.get(i);
        Optional<Display> optionalDisplay = DisplayManager.getInstance().getDefaultDisplay(componentContainer.getContext());
        if (optionalDisplay != null && optionalDisplay.isPresent()) {
            int edgeLength = optionalDisplay.get().getAttributes().width / column;
            component.setWidth(edgeLength - 20);
            component.setHeight(edgeLength - 20);
            component.setMarginsLeftAndRight(10, 10);
            component.setMarginsTopAndBottom(10, 10);
        }
        return component;
    }
}
